package com.mz.ieann.dokit.utils

import android.content.Context
import android.os.Environment
import android.os.Parcelable
import android.util.Log
import androidx.annotation.NonNull
import com.alibaba.fastjson.JSON
import java.io.*
import java.nio.charset.StandardCharsets

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> des
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2021 2021/11/14 12:45
 */
object FileRead {

    /**
     * 加载SD卡文件，路径/mnt/sdcard/name.txt，读行，非json
     */
    fun readCard(context : Context, name : String) : List<String> {
        if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
            return emptyList()
        }
        val result = ArrayList<String>()
        var input : FileInputStream? = null
        var inputReader : InputStreamReader? = null
        var reader : BufferedReader? = null
        try {
            val file = File(Environment.getExternalStorageDirectory(), name)
            Log.v("aaaa", "file path : ${file.path}")
            if (!file.exists()){
                return readAsset(context, name)
            }
            input = FileInputStream(file)
            inputReader = InputStreamReader(input, StandardCharsets.UTF_8)
            reader = BufferedReader(inputReader)
            var line = ""
            while (reader.readLine()?.also { line = it } != null) {
                result.add(line)
            }
        }catch (e : Exception){
            e.printStackTrace()
            LogUtils.e("error: $e")
        }finally {
            reader?.close()
            inputReader?.close()
            input?.close()
        }
        return result
    }

    /**
     * 读取asset文件，读行，非json
     */
    fun readAsset(context : Context, name : String) : List<String> {
        val result = ArrayList<String>()

        var input : InputStream? = null
        var inputReader : InputStreamReader? = null
        var reader : BufferedReader? = null
        try {
            input = context.applicationContext.assets.open(name)
            inputReader = InputStreamReader(input, StandardCharsets.UTF_8)
            reader = BufferedReader(inputReader)
            var line = ""
            while (reader.readLine()?.also { line = it } != null) {
                result.add(line)
            }
        }catch (e : Exception){
            e.printStackTrace()
            LogUtils.e("error: $e")
        }finally {
            reader?.close()
            inputReader?.close()
            input?.close()
        }
        return result
    }

    /**
     * 读取assets文件，返回原数据
     */
    fun readAssets(context : Context, @NonNull name : String) : String?{
        var result : String? = null
        var input : InputStream? = null
        try {
            input = context.applicationContext.assets.open(name)
            val bytes = ByteArray(input.available())
            input.read(bytes)
            result = String(bytes)
        }catch (e : Exception){
            LogUtils.e("error: $e")
            e.printStackTrace()
        }finally {
            runCatching {
                input?.close()
            }
        }
        return result
    }

    /**
     * 读取asset文件，返回 Parcelable 类型
     */
    fun <T : Parcelable> readAssets(context : Context, @NonNull any: Class<T>, @NonNull name : String) : T?{
        val result = readAssets(context, name)
        return runCatching {
            JSON.parseObject(result, any)
        }.onFailure {
            LogUtils.e("error: $it")
        }.getOrNull()
    }

}